const app = getApp()
const api = require('../../utils/api')

Page({
  data: {
    timeRange: 'day', // day, week, month
    showDayView: true,
    showWeekView: false,
    showMonthView: false,
    currentDate: '',
    today: '',           // YYYY-MM-DD 格式
    selectedDateStr: '', // YYYY-MM-DD 格式
    selectedDate: null,  // 存储选中的日期对象
    qualityLevel: '--',
    qualityClass: '',
    todayRecords: [], // 改为数组存储所有记录
    chartData: [],
    xLabels: [],
    statistics: {
      average: '--',
      max: '--',
      min: '--'
    },
    lastFetchTime: null,  // 记录上次获取数据的时间
    needRefresh: true,    // 是否需要刷新数据的标记
    cachedData: {
      day: {},    // 按日期缓存日视图数据
      week: {},   // 按周缓存周视图数据
      month: {}   // 按月缓存月视图数据
    },
    glucoseTarget: 6.1 // 添加血糖目标值
  },

  onLoad() {
    // 设置血糖目标值
    const settings = wx.getStorageSync('glucoseSettings') || {};
    this.setData({
      glucoseTarget: settings.targetGlucose || 6.1,
      needRefresh: false // 默认不需要刷新数据
    });

    this.initDates();
  },

  onShow() {
    console.log('bloodsugardetail onShow');
    
    // 初始化日期（如果需要）
    if (!this.data.selectedDateStr) {
      this.initDates();
    }
    
    // 设置强制刷新标志
    wx.setStorageSync('blood_sugar_detail_needs_refresh', true);
    
    // 强制刷新机制 - 每次显示页面时都强制刷新数据
    this.setData({ 
      needRefresh: true,
      lastFetchTime: null 
    });
    this.clearAllCache();
    
    // 立即刷新数据 
    this.fetchData();
  },

  initDates() {
    const now = new Date()
    const today = now.toISOString().split('T')[0]  // YYYY-MM-DD 格式
    const currentDate = this.formatDateToString(now)
    
    this.setData({
      today,
      selectedDateStr: today,
      currentDate,
      selectedDate: now
    })
  },

  formatDateToString(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${year}年${month}月${day}日`
  },

  onSelectDate(e) {
    const date = e.detail.value
    const selectedDate = new Date(date)
    const currentDate = this.formatDateToString(selectedDate)
    
    // 如果选择了不同的日期，需要刷新数据
    const needRefresh = date !== this.data.selectedDateStr
    
    this.setData({
      currentDate,
      selectedDateStr: date,
      selectedDate,
      needRefresh
    }, () => {
      // 只有需要刷新时才获取数据
      if (needRefresh) {
        this.fetchData()
      }
    })
  },

  async fetchData() {
    try {
      const { timeRange, selectedDateStr } = this.data;
      
      // 清除旧缓存
      this.clearCache(timeRange);
      
      // 检查缓存
      const cacheKey = `${timeRange}_${selectedDateStr}`;
      if (this.data.cachedData[timeRange][cacheKey]) {
        // 使用缓存数据
        const cachedData = this.data.cachedData[timeRange][cacheKey];
        this.updateViewWithData(timeRange, cachedData);
        return;
      }

      const startDate = new Date(selectedDateStr);
      startDate.setHours(0, 0, 0, 0);
      
      let endDate = new Date(startDate);
      // 根据时间范围设置不同的日期范围
      switch(timeRange) {
        case 'week':
          // 获取本周的数据
          startDate.setDate(startDate.getDate() - startDate.getDay()); // 设置为本周日
          endDate = new Date(startDate);
          endDate.setDate(startDate.getDate() + 7);
          break;
        case 'month':
          // 获取本月的数据
          startDate.setDate(1); // 设置为本月第一天
          endDate = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 1);
          break;
        default: // day
          endDate.setDate(startDate.getDate() + 1);
          break;
      }

      const records = await api.health.getRecords({ 
        type: 'glucose',
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString()
      });

      // 缓存数据
      this.setData({
        [`cachedData.${timeRange}.${cacheKey}`]: records,
        lastFetchTime: Date.now(), // 记录最后获取数据的时间戳
        needRefresh: false // 重置刷新标志
      });

      // 更新视图
      this.updateViewWithData(timeRange, records);

    } catch (err) {
      console.error('获取记录失败:', err.message || err);
      wx.showToast({
        title: '获取数据失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  formatTime(timestamp, format = 'date') {
    // 如果输入无效，返回空字符串
    if (!timestamp) return format === 'time' ? '--:--' : '--/--';
    
    // 确保使用有效的日期对象
    let date;
    try {
      // 处理数值型时间戳和日期字符串
      if (typeof timestamp === 'number') {
        date = new Date(timestamp);
      } else if (typeof timestamp === 'string') {
        date = new Date(timestamp);
      } else if (timestamp instanceof Date) {
        date = timestamp;
      } else {
        return format === 'time' ? '--:--' : '--/--';
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return format === 'time' ? '--:--' : '--/--';
      }
    } catch (e) {
      console.error('时间格式化错误:', e);
      return format === 'time' ? '--:--' : '--/--';
    }
    
    // 根据请求的格式返回
    if (format === 'time') {
      return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },

  getQualityLevel(value) {
    if (!value) return { level: '--', class: '' }
    if (value > 13.9) return { level: '高', class: 'very-high' }
    if (value > 11.0) return { level: '较高', class: 'high' }
    if (value < 2.8) return { level: '低', class: 'very-low' }
    if (value < 3.9) return { level: '较低', class: 'low' }
    return { level: '正常', class: 'normal' }
  },

  changeTimeRange(e) {
    const range = e.currentTarget.dataset.range
    const needRefresh = range !== this.data.timeRange
    
    this.setData({
      timeRange: range,
      showDayView: range === 'day',
      showWeekView: range === 'week',
      showMonthView: range === 'month',
      needRefresh
    }, () => {
      if (needRefresh) {
        this.fetchData()
      }
    })
  },

  showActionSheet() {
    wx.showActionSheet({
      itemList: ['数据记录', '手动添加', '血糖设置'],
      itemColor: '#333333',
      success: (res) => {
        switch (res.tapIndex) {
          case 0: // 数据记录
            wx.navigateTo({
              url: '/pages/history/history?type=glucose',
              events: {
                // 数据变更事件
                dataChanged: (data) => {
                  console.log('收到历史页面数据变更事件:', data);
                  this.forceRefresh();
                }
              },
              success: (res) => {
                res.eventChannel.on('dataChanged', (data) => {
                  console.log('通过事件通道收到历史页面数据变更:', data);
                  this.forceRefresh();
                });
              }
            });
            break;
          case 1: // 手动添加
            wx.navigateTo({
              url: '/pages/record/record?type=glucose',
              events: {
                recordAdded: (data) => {
                  console.log('收到记录添加事件:', data);
                  this.forceRefresh();
                }
              },
              success: (res) => {
                res.eventChannel.on('recordAdded', (data) => {
                  console.log('通过事件通道收到记录添加:', data);
                  this.forceRefresh();
                });
              }
            });
            break;
          case 2: // 血糖设置
            wx.navigateTo({
              url: '/pages/settings/glucoseSettings'
            });
            break;
        }
      }
    });
  },

  showQualityInfo() {
    wx.showModal({
      title: '血糖质量评价说明',
      content: '血糖质量评价标准：\n正常：3.9-11.0 mmol/L\n较高：11.1-13.9 mmol/L\n高：>13.9 mmol/L\n较低：2.8-3.8 mmol/L\n低：<2.8 mmol/L',
      showCancel: false
    })
  },

  // 了解血糖按钮点击事件
  onLearnMoreTap() {
    console.log('了解血糖按钮被点击')
    wx.navigateTo({
      url: '../bloodsugar/knowledge'
    })
  },

  // 更新视图的逻辑
  updateViewWithData(timeRange, records) {
    switch(timeRange) {
      case 'day':
        if (records && records.length > 0) {
          // 确保数据是最新的排序（按时间倒序）
          const todayRecords = records.map(record => {
            // 使用可用的时间字段，优先使用measuredAt
            const timeField = record.measuredAt || record.timestamp;
            return {
              ...record,
              timeStr: this.formatTime(timeField, 'time'),
              value: parseFloat(record.value).toFixed(1) // 确保值格式一致
            };
          }).sort((a, b) => {
            // 使用可用的时间字段排序
            const aTime = new Date(a.measuredAt || a.timestamp).getTime();
            const bTime = new Date(b.measuredAt || b.timestamp).getTime();
            return bTime - aTime; // 降序排列
          });

          const totalValue = todayRecords.reduce((sum, record) => 
            sum + parseFloat(record.value), 0);
          const averageValue = (totalValue / todayRecords.length).toFixed(1);
          const qualityInfo = this.getQualityLevel(averageValue);
          
          this.setData({
            todayRecords,
            qualityLevel: qualityInfo.level,
            qualityClass: qualityInfo.class,
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          });
        } else {
          this.setData({
            todayRecords: [],
            qualityLevel: '--',
            qualityClass: '',
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          });
        }
        break;
      case 'week':
        if (records && records.length > 0) {
          // 1. 计算平均血糖值
          const totalValue = records.reduce((sum, record) => 
            sum + parseFloat(record.value), 0)
          const averageValue = (totalValue / records.length).toFixed(1)

          // 2. 准备图表数据 - 修改为显示每条记录
          // 按照时间先后排序记录
          records.sort((a, b) => {
            const aTime = new Date(a.measuredAt || a.timestamp).getTime();
            const bTime = new Date(b.measuredAt || b.timestamp).getTime();
            return aTime - bTime;
          });

          // 提取每条记录的数值和对应的标签
          const chartData = [];
          const xLabels = [];

          records.forEach(record => {
            // 添加血糖值到图表数据
            chartData.push(parseFloat(record.value).toFixed(1));
            
            // 创建包含日期和时间的标签
            const recordDate = new Date(record.measuredAt || record.timestamp);
            const month = recordDate.getMonth() + 1;
            const date = recordDate.getDate();
            const hours = recordDate.getHours().toString().padStart(2, '0');
            const minutes = recordDate.getMinutes().toString().padStart(2, '0');
            
            // 标签格式：MM.DD HH:MM
            xLabels.push(`${month}.${date} ${hours}:${minutes}`);
          });

          // 4. 更新统计数据
          const validValues = records.map(r => parseFloat(r.value))
          const statistics = {
            average: averageValue,
            max: Math.max(...validValues).toFixed(1),
            min: Math.min(...validValues).toFixed(1)
          }

          // 正确格式化图表数据，将简单数组转换为图表组件期望的对象数组格式
          const formattedChartData = [
            {
              name: '血糖',
              data: chartData,
              color: '#4CAF50'
            }
          ];

          this.setData({
            showWeekView: true,
            showDayView: false,
            showMonthView: false,
            statistics,
            chartData: formattedChartData,
            xLabels: xLabels,
            glucoseTarget: parseFloat(averageValue),
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          })
        } else {
          this.setData({
            showWeekView: true,
            showDayView: false,
            showMonthView: false,
            statistics: {
              average: '--',
              max: '--',
              min: '--'
            },
            chartData: [],
            xLabels: [],
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          })
        }
        break
      case 'month':
        if (records && records.length > 0) {
          // 1. 计算平均血糖值
          const totalValue = records.reduce((sum, record) => 
            sum + parseFloat(record.value), 0)
          const averageValue = (totalValue / records.length).toFixed(1)

          // 2. 准备图表数据 - 修改为显示每条记录
          // 按照时间先后排序记录
          records.sort((a, b) => {
            const aTime = new Date(a.measuredAt || a.timestamp).getTime();
            const bTime = new Date(b.measuredAt || b.timestamp).getTime();
            return aTime - bTime;
          });

          // 提取每条记录的数值和对应的标签
          const chartData = [];
          const xLabels = [];

          records.forEach(record => {
            // 添加血糖值到图表数据
            chartData.push(parseFloat(record.value).toFixed(1));
            
            // 创建包含日期的标签
            const recordDate = new Date(record.measuredAt || record.timestamp);
            const date = recordDate.getDate();
            
            // 标签格式：DD
            xLabels.push(`${date}日`);
          });

          // 4. 更新统计数据
          const validValues = records.map(r => parseFloat(r.value))
          const statistics = {
            average: averageValue,
            max: Math.max(...validValues).toFixed(1),
            min: Math.min(...validValues).toFixed(1)
          }

          // 正确格式化图表数据，将简单数组转换为图表组件期望的对象数组格式
          const formattedChartData = [
            {
              name: '血糖',
              data: chartData,
              color: '#4CAF50'
            }
          ];

          this.setData({
            showWeekView: false,
            showDayView: false,
            showMonthView: true,
            statistics,
            chartData: formattedChartData,
            xLabels: xLabels,
            glucoseTarget: parseFloat(averageValue),
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          })
        } else {
          this.setData({
            showWeekView: false,
            showDayView: false,
            showMonthView: true,
            statistics: {
              average: '--',
              max: '--',
              min: '--'
            },
            chartData: [],
            xLabels: [],
            lastFetchTime: new Date().getTime(),
            needRefresh: false
          })
        }
        break
    }
  },

  // 清除所有缓存
  clearAllCache() {
    console.log('清除所有数据缓存');
    this.setData({
      cachedData: {
        day: {},
        week: {},
        month: {}
      },
      lastFetchTime: null
    });
  },

  // 原始的clearCache方法修改为处理特定时间范围
  clearCache(timeRange) {
    if (timeRange) {
      // 清除指定时间范围的缓存
      console.log(`清除${timeRange}视图缓存`);
      this.setData({
        [`cachedData.${timeRange}`]: {}
      });
    } else {
      // 如果没有指定时间范围，则调用clearAllCache
      this.clearAllCache();
    }
  },

  onReady() {
    // 初始化数据
    this.fetchData();
  },

  onHide() {
    console.log('页面隐藏')
  },
  
  onUnload() {
    console.log('页面卸载')
  },

  // 强制刷新数据
  forceRefresh() {
    console.log('强制刷新血糖数据');
    this.clearAllCache();
    this.setData({ 
      needRefresh: true,
      lastFetchTime: null 
    });
    this.fetchData();
  },
})